<?php

namespace app\api\services\v1\user;

use app\admin\model\DataUser;
use app\api\services\BaseServices;

/**
 * 登陆服务
 */
class UserService extends BaseServices
{

    /**
     * 密码登陆处理
     * @param $data
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public  function Login($data,$ip): array
    {
        $user = $this->getModel()->where(['mobile'=>$data['phone'],'usertype'=>$data['usertype']])->findOrEmpty();
        if($user->isEmpty()) return [];
        $user->inc('login_num')->update([
            'login_at' => date('Y-m-d H:i:s'),
            'login_ip' => $ip,
        ]);
       $user= $user->toArray();
       if(isset($data['password'])){
           if(md5($data['password']) !== $user['password']) return [];
       }
       $token = $this->createToken($user);

       return ['user'=>$user,'token'=>$token['token']];
    }



    public function Base($data,$id): bool
    {
        $user = $this->getModel()->where(['id'=>$id])->findOrEmpty();
        if($user->isEmpty()) return false;
        if($user->save($data)){
            return true;
        }else{
            return false;
        }
    }



    private function getModel(){
       return new DataUser();
    }


}